/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dubbo.rpc.cluster.router.condition.config;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.RouterFactory;

/**
 * Application level router factory
 */
@Activate(order = 200)
public class AppRouterFactory implements RouterFactory {
    public static final String NAME = "app";

    private volatile Router router;

    /**
     * 这个是针对应用级别的路由监听和获取
     * 其实这里做的事情就是根据本应用的名字从配置中心获取到应用对应的路由配置，然后生成一个AppRouter对象
     * 返回这个路由，作为服务调用路由的规则之一，然后还进行了监听，当动态路由发生变化的时候及时更新到本地配置中
     * 所以这里dubbo与注册中心如zookeeper建立了订阅关系，也就是应用对路由的zookeeper的节点进行了监听
     * 监听和获取的节点是：/dubbo/config/dubbo/dubbo-demo-annotation-consumer.condition-router(条件路由）
     * 内容如下；
     * enabled: true
     * force: true
     * runtime: false
     * conditions:
     *   - '=> host != 172.22.3.91'
     *   表示所有的请求不能是上面的这个ip
     * @param url url
     * @return
     */

    @Override
    public Router getRouter(URL url) {
        if (router != null) {
            return router;
        }
        synchronized (this) {
            if (router == null) {
                router = createRouter(url);
            }
        }
        return router;
    }

    private Router createRouter(URL url) {
        return new AppRouter(url);
    }
}
